<script setup lang="ts">
import { reactive, computed, ref } from "vue";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
// 导入请求方法
import { userLogin } from "../api/login.ts";
// 导入消息提示内框
import ShowMessage from "../utils/ShowMessage.ts";
// 引入路由
import { useRouter } from "vue-router";
let router = useRouter();

// 引入piniz仓库
import useStore from "../stores/index.ts";
let store = useStore();

interface FormState {
  username: string;
  password: string;
}

// 登录加载中状态
let loginLoading = ref(false);

const formState = reactive<FormState>({
  username: "",
  password: "",
});

const onFinish = async (values: any) => {
  loginLoading.value = true; //登录加载中

  console.log("Success:", values);
  //在此发送请求
  let res = await userLogin(values);
  console.log(res);
  loginLoading.value = false; //登录加载完毕
  if (res.meta.status == 200) {
    // 登录成功
    // 1、弹出消息提示  登录成功
    ShowMessage("登陆成功", "success");
    // 2、将返回的token 存到本地
    localStorage.setItem("token", res.data.token);
    // 3、将用户名存到本地
    localStorage.setItem("username", res.data.username);
    // 4、将token存到pinia仓库中
    store.setToken(res.data.token);

    // 5、跳转到首页
    router.push("/home");
  } else {
    console.log(res);
    // 登录失败
    // 弹出消息提示框，提示失败信息
    ShowMessage(res.meta.msg, "error");
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const disabled = computed(() => {
  return !(formState.username && formState.password);
});
</script>
<template>
  <div>
    <a-form
    :model="formState"
    name="horizontal_login"
    class="form"
    autocomplete="off"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      label="Username"
      name="username"
      :rules="[{ required: true, message: 'Please input your username!' }]"
    >
      <a-input v-model:value="formState.username">
        <template #prefix>
          <UserOutlined class="site-form-item-icon" />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      label="Password"
      name="password"
      :rules="[{ required: true, message: 'Please input your password!' }]"
    >
      <a-input-password v-model:value="formState.password">
        <template #prefix>
          <LockOutlined class="site-form-item-icon" />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item>
      <a-button :disabled="disabled" type="primary" html-type="submit">
        <div v-if="loginLoading">
          <a-spin />
        </div>
        <div v-else>登录</div>
      </a-button>
    </a-form-item>
  </a-form>
  </div>
</template>
<style scoped>
.form {
  width: 600px;
}
</style>
